﻿<?php
#error_reporting(0); //容错
header('Content-Type: text/html; charset=utf-8'); //强制UTF-8输出
$url = isset($_POST['url']) ? $_POST['url'] : '';  //使用isset检查 修复5.3下的错误提示

if($url) {
	#$string = file_get_contents($url);
	$data = file_get_contents($url);
	$string = iconv("GBK", "GBK", $data); // 贴吧GBK编码 转换为UTF-8
	preg_match_all('/<a href=\"\/p\/.*\?pn=(.*)\">尾页<\/a>/i', $string, $output); //提取分页
	#var_dump($output);
	$end = sizeof($output);
	#$end = $output['1']['0'];  //分页总量
	
	$murl = array();              //生成URL列表的数组 用于多线程抓取
	for ($i = 1; $i <= $end; $i++) {  //循环生成
		$murl[] = $url.'?pn='.$i;  
	}
	#var_dump($murl);
	$run = multiple_threads_request($murl); //多线程请求页面内容
	$content = implode("\r\n",$run); //合并页面内容
	#echo $content;
	$pattern = '/[a-z0-9_\-\+]+@[a-z0-9\-]+\.([a-z]{2,3})(?:\.[a-z]{2})?/i';
	preg_match_all($pattern, $content,$matches); //提取邮箱地址
	$list = array_unique($matches[0]);  //去除重复邮箱地址
	$email = implode("\r\n",$list);
	$count = count($list);
	echo "<div class=\"col-xs-6 col-md-offset-2\">
				<p>总计采集到 $count 个Email邮箱地址</p>
				<textarea class=\"form-control\" onclick=\"this.focus();this.select()\" readonly=\"readonly\" rows=\"10\">$email</textarea>
			  </div>";
} else {
	echo "
	<div class=\"alert alert-warning\">
	  <strong>抱歉!</strong> 你可能没有输入完整的贴吧帖子地址哦!
	</div>	
	";
}

//CURL 多线程请求函数封装
function multiple_threads_request($nodes){ 
        $mh = curl_multi_init(); 
        $curl_array = array(); 
        foreach($nodes as $i => $url) { 
            $curl_array[$i] = curl_init($url); 
            curl_setopt($curl_array[$i], CURLOPT_RETURNTRANSFER, true); 
            curl_multi_add_handle($mh, $curl_array[$i]); 
        } 
        $running = NULL; 
        do { 
            usleep(10000);
            curl_multi_exec($mh,$running); 
        } while($running > 0); 
        $res = array(); 
        foreach($nodes as $i => $url)  { 
            $res[$url] = curl_multi_getcontent($curl_array[$i]); 
        } 
        foreach($nodes as $i => $url){ 
            curl_multi_remove_handle($mh, $curl_array[$i]); 
        } 
        curl_multi_close($mh);        
        return $res; 
}
?>
